# ------------------------------------------------------------------------------------------------
### Generate Table 12: Number of municipalities by treatment type and status
# ------------------------------------------------------------------------------------------------

# Load the data
load("../data/processed/LGBTQ_election_data_w1w2.Rda")

# Create cutoff samples
LGBTQ_election_data_w1w2_cutoff <- create_cutoff_sample(LGBTQ_election_data_w1w2, wave = "w1w2")

# List large cities for the count -----
cities_300k <- c("1465", # Warsaw
                 "1061", # Lodz
                 "1261", # Krakow
                 "0264", # Wroclaw
                 "3064", # Poznan
                 "2261", # Gdansk
                 "3262", # Szczecin
                 "0461", # Bydgoszcz
                 "0663", # Lublin
                 "2469") # Katowice

# Subset to 2019 and add large city indicators ----
mun_w1w2 <- LGBTQ_election_data_w1w2 %>%
  filter(eyear == 2019) %>%
  mutate(city_300k = +(id_county %in% cities_300k))

mun_cutoff_w1w2  <- LGBTQ_election_data_w1w2_cutoff %>% 
  filter(eyear == 2019) %>%
  mutate(city_300k = +(id_county %in% cities_300k))

# Define count functions ----
count_pre <- function(df, cond_str) {
  mask <- with(df, eval(parse(text = cond_str)) & (wave_id == 1))
  sum(mask, na.rm = TRUE)
}
count_tot <- function(df, cond_str) {
  mask <- with(df, eval(parse(text = cond_str)) & (wave_id %in% c(1,2)))
  sum(mask, na.rm = TRUE)
}
count_after <- function(df, cond_str) {
  mask <- with(df, eval(parse(text = cond_str)) & (wave_id == 2))
  sum(mask, na.rm = TRUE)
}
count_never <- function(df, cond_str) {
  mask <- with(df, eval(parse(text = cond_str)) & (wave_id == 0))
  sum(mask, na.rm = TRUE)
}


# Define subsets of municipalities ----
categories <- list(
  "One Level"                          = "sum_count_any_type == 1",
  "Two Levels"                         = "sum_count_any_type == 2",
  "Three Levels"                       = "sum_count_any_type == 3",
  "One Type"                           = "sum_count_any_level == 1",
  "Two Types"                          = "sum_count_any_level == 2",
  "Province Level"                     = "province_any_type == 1",
  "County Level"                       = "county_any_type == 1",
  "Municipality Level"                 = "municipality_any_type == 1",
  "Resolution against LGBT ideology"   = "any_level_type_1 == 1",
  "Charter of the Rights of the Family"= "any_level_type_2 == 1",
  "No municipalities $>$ 300k residents" = "city_300k == 0",
  "No proposing municipalities"        = "any_level_proposed == 0"
)

# LaTeX table head ----
latex <- c(
  "\\begin{table}[ht]",
  "\\centering",
  "\\renewcommand{\\arraystretch}{1.2}",
  "\\begin{tabular}{l>{\\centering\\arraybackslash}m{1.25cm}>{\\centering\\arraybackslash}m{2.25cm}>{\\centering\\arraybackslash}m{2.25cm}>{\\centering\\arraybackslash}m{1.25cm}}",
  "\\hline",
  "\\hline",
  "Type of Treatment & Never Treated & Treated before 2019 election & Treated only after 2019 election & Total Treated\\\\",
  "\\hline"
)

# Full dataset counts ----
## totals -----
full_never <- nrow(filter(mun_w1w2, wave_id == 0))
full_pre   <- nrow(filter(mun_w1w2, wave_id == 1))
full_tot   <- nrow(filter(mun_w1w2, wave_id %in% c(1,2)))
full_after <- nrow(filter(mun_w1w2, wave_id == 2))

latex <- c(latex,
           sprintf("\\textbf{All municipalities} & %d & %d & %d & %d\\\\", 
                   full_never, full_pre, full_after, full_tot),
           "\\hline",
           "\\addlinespace"
)

## subcategories ----
for(sub in names(categories)) {
  cond  <- categories[[sub]]
  pre   <- count_pre(mun_w1w2, cond)
  tot   <- count_tot(mun_w1w2, cond)
  after <- count_after(mun_w1w2, cond)
  
  # insert dashline *before* the target row
  if (sub == "No municipalities $>$ 300k residents") {
    latex <- c(latex, "\\hdashline")
  }
  
  never_disp <- if (sub %in% c("No municipalities $>$ 300k residents", "No proposing municipalities")) {
    count_never(mun_w1w2, cond)
  } else {
    "''"
  }
  
  latex <- c(latex,
             sprintf("\\quad %s & %s & %d & %d & %d\\\\",
                     sub, never_disp, pre, after, tot)
  )
}


# <50km  dataset counts ----
## totals -----
cut_never <- nrow(filter(mun_cutoff_w1w2, wave_id == 0))
cut_pre   <- nrow(filter(mun_cutoff_w1w2, wave_id == 1))
cut_tot   <- nrow(filter(mun_cutoff_w1w2, wave_id %in% c(1,2)))
cut_after <- nrow(filter(mun_cutoff_w1w2, wave_id == 2))

latex <- c(latex,
           "\\addlinespace",
           "\\hline",
           sprintf("\\textbf{$<$ 50km from treatment boundary} & %d & %d & %d & %d\\\\",
                   cut_never, cut_pre, cut_after, cut_tot),
           "\\hline",
           "\\addlinespace"
)

## subcategories ----
for(sub in names(categories)) {
  cond  <- categories[[sub]]
  pre   <- count_pre(mun_cutoff_w1w2,  cond)
  tot   <- count_tot(mun_cutoff_w1w2, cond)
  after <- count_after(mun_cutoff_w1w2, cond)
  
  # insert dashline *before* the target row
  if (sub == "No municipalities $>$ 300k residents") {
    latex <- c(latex, "\\hdashline")
  }
  
  never_disp <- if (sub %in% c("No municipalities $>$ 300k residents", "No proposing municipalities")) {
    count_never(mun_cutoff_w1w2, cond)
  } else {
    "''"
  }
  
  latex <- c(latex,
             sprintf("\\quad %s & %s & %d & %d & %d\\\\",
                     sub, never_disp, pre, after, tot)
  )
}

# Close table ----
latex <- c(latex,
           "\\addlinespace",
           "\\hline",
           "\\end{tabular}",
           "\\caption{Number of Municipalities by Treatment Status}",
           "\\label{tab:units_by_treatment}",
           "\\end{table}"
)


# Save the table to a .txt file
writeLines(latex, "../output/tables/table12.txt")